<template>
  <div class="picking zy-content ">
    <!--查询条件-->
    <div class="searchBox search-box-layout">
      <Row :gutter="24">
        <Col span="4">
          <div>
            <p class="label">{{$t('equipCheck.Result')}}</p>
            <div class="ipt">
              <Select v-model="searchParams.inventoryResult"
                      filterable clearable :placeholder="`${$t('common.selectInfo')}`">
                <Option v-for="(item,index) of statusList" :value="item.value" :key="index">{{ item.label }}</Option>
              </Select>
            </div>
          </div>
        </Col>
        <Col span="4">
          <div>
            <p class="label">{{$t('equipCheck.Time')}}</p>
            <div class="ipt">
              <Date-picker v-model="searchParams.date"
                           format="yyyy-MM-dd HH:mm:ss"
                           type="datetimerange"
                           placement="bottom-end" :placeholder="`${$t('common.selectInfo')}`" style="width: 100%"></Date-picker>
            </div>
          </div>
        </Col>
        <Col span="4">
          <div>
            <p class="label">{{$t('equipCheck.ListByEntity')}}</p>
            <div class="ipt">
              <Select v-model="searchParams.companyCode"
                      filterable
                      @on-change="companySelectChange"
                      clearable
                      :placeholder="`${$t('common.selectInfo')}`">
                <Option v-for="(item,index) of companyList" :value="item.code" :key="index">{{ item.name }}</Option>
              </Select>
            </div>
          </div>
        </Col>
        <Col span="4">
          <div>
            <p class="label">{{$t('equipCheck.ListByFactory')}}</p>
            <div class="ipt">
              <Select v-model="searchParams.factoryCode"
                      filterable clearable :placeholder="`${$t('common.selectInfo')}`">
                <Option v-for="(item,index) of factoryList"
                        :value="item.code"
                        :key="index">{{ item.name }}
                </Option>
              </Select>
            </div>
          </div>
        </Col>
        <Col span="4">
          <div>
            <p class="label">{{$t('equipCheck.CheckByEntity')}}</p>
            <div class="ipt">
              <Select @on-change="companySelectChanges" v-model="searchParams.inventoryCompanyCode"
                      filterable clearable :placeholder="`${$t('common.selectInfo')}`">
                <Option v-for="(item,index) of companyList" :value="item.code" :key="index">{{ item.name }}</Option>
              </Select>
            </div>
          </div>
        </Col>
        <Col span="4">
          <div>
            <p class="label">{{$t('equipCheck.CheckByFactory')}}</p>
            <div class="ipt">
              <Select v-model="searchParams.inventoryFactoryCode"
                      filterable clearable :placeholder="`${$t('common.selectInfo')}`">
                <Option v-for="(item,index) of factoryLists" :value="item.code" :key="index">{{ item.name }}</Option>
              </Select>
            </div>
          </div>
        </Col>
        <Col span="4">
          <div>
            <p class="label">{{$t('ledger.AssetNo')}}</p>
            <div class="ipt">
              <Select v-model="searchParams.assetsNo"
                      filterable clearable :placeholder="`${$t('common.selectInfo')}`">
                <Option v-for="(item,index) of assetsNoList" :value="item.assetsNo" :key="index">{{ item.assetsNo }}</Option>
              </Select>
            </div>
          </div>
        </Col>
        <Col span="4">
          <div>
            <p class="label">{{$t('maintenance.EquipmentNo')}}</p>
            <div class="ipt">
              <Select v-model="searchParams.deviceNo"
                      filterable clearable :placeholder="`${$t('common.selectInfo')}`">
                <Option v-for="(item,index) of noList" :value="item.deviceNo" :key="index">{{ item.deviceNo }}</Option>
              </Select>
            </div>
          </div>
        </Col>
        <Col span="4">
          <div>
            <p class="label">{{$t('equipCheck.CheckedBy')}}</p>
            <div class="ipt">
              <Select clearable v-model="searchParams.inventoryBy" filterable>
                <Option v-for="(item,index) in inventoryByList" :value="item.id" :key="index">{{item.realname}}</Option>
              </Select>
            </div>
          </div>
        </Col>
        <Col span="4">
          <div>
            <p class="label hide-label">--</p>
            <div class="ipt">
              <Button  v-has="'inventorySearch'" class="search-btn" type="primary" @click="changeNum()">
                {{ $t('preliminary.Search') }}
              </Button>   <!--查询-->
              <Button
                  v-has="'inventorySearch'"
                  class="reset-btn"
                  @click="reset()"
              >{{ $t('common.reset') }}
              </Button>
            </div>
          </div>
        </Col>
      </Row>
    </div>
    <div class="list-layout mt16">
      <div class="btns clear">
        <span class="title">{{ $t('common.listInformation') }}</span>
        <Button v-has="'inventoryExport'"  @click="handleOutRecords">{{ $t('equipCheck.ExportCountingRecords') }}</Button>
        <Button  @click="helpVisible=true">{{ $t('common.help') }}</Button>
      </div>
      <!--表格-->
      <div class="tableContent">
        <Table  class="resizable-table" border @on-column-width-resize="onColumnWidthResize" ellipsis ref="selection" :columns="columns" :data="dataSource"
               @on-selection-change="handleSelectionChange">
        </Table>
      </div>
      <!--分页-->
      <div class="pageWrap mt16">
        <pageLeftTitle :total="total" />
        <Page :total="total" :page-size="pageSize" :page-size-opts="$variable.pageSizes" :current="pageNum"
              @on-change="changePageNum" @on-page-size-change="changePageSize" show-sizer show-total/>
      </div>
    </div>
    <Modal :mask-closable="false"
        v-model="helpVisible"
        title="帮助"
        class="modal-content-layout"
    >
      <p class="help">对比结果：</p>
      <p class="help"> 一致：盘点记录的位置与设备台账位置一致。</p>
      <p class="help">不一致：盘点记录的位置与设备台账位置不一致。</p>
      <p class="help">新增：盘点记录存在该设备，但设备台账不存在该设备（任何区域都不存在）。</p>
      <p class="help">缺失：盘点记录不存在该设备，但是设备台账存在该设备。</p>
      <div slot="footer"></div>
    </Modal>
  </div>
</template>

<script>

import fileDownload from "js-file-download";
import {findOrgByLevel, getUsers, deviceNoAndAssetsNo} from "@/api";
import moment from "moment";
import toggleTableOperation from "@/mixins/toggleTableOperation";
export default {
  name: "equipCheck",
  mixins:[toggleTableOperation],
  components: {},
  data() {
    return {
      helpVisible: false,
      ids: '',
      pageNum: 1,
      pageSize: 10,
      total: 0,
      searchParams: {},
      statusList: [
        {label: "全部", value: ''},
        {label: "不一致", value: 0},
        {label: "一致", value: 1},
        {label: "缺失", value: 2},
        {label: "新增", value: 3},
      ],
      columns: [
        {
          //  title: '盘点时间',
          title: `${this.$t('批次号')}`,
          key: 'inventoryNo',
          align: 'center',
          minWidth: 180,
          resizable: true
        },
        {
        //  title: '盘点时间',
          title: `${this.$t('equipCheck.Time')}`,
          key: 'inventoryDate',
          align: 'center',
          minWidth: 180,
          resizable: true
        },
        {
         // title: '设备状态',
          title: `${this.$t('equipCheck.Status')}`,
          key: 'deviceStatusStr',
          align: 'center',
          minWidth: 100,
          resizable: true
        },
        {
          title: `${ this.$t('equipCheck.SerialNo') }`,
          key: 'deviceMId',
          align: 'center',
          minWidth: 180,
          resizable: true
        },
        {
          title: `${ this.$t('maintenance.EquipmentNo') }`,
          key: 'deviceNo',
          align: 'center',
          minWidth: 140,
          resizable: true
        },
        {
         title: `${ this.$t('maintenance.EquipmentName') }`,
          key: 'deviceName',
          align: 'center',
          minWidth: 140,
          resizable: true
        },
        {
          title: `${ this.$t('equipCheck.AssetNo') }`,
          key: 'assetsNo',
          align: 'center',
          minWidth: 120,
          resizable: true
        },
        {
          title: `${ this.$t('equipCheck.Model') }`,
          key: 'specification',
          align: 'center',
          minWidth: 120,
          resizable: true
        },
        {
          //title: '台账公司',
           title: `${this.$t('equipCheck.ListByEntity')}`,
          key: 'companyName',
          align: 'center',
          minWidth: 200,
          resizable: true
        },
        {
         // title: '台账厂区',
           title: `${this.$t('equipCheck.ListByFactory')}`,
          key: 'factoryName',
          align: 'center',
          minWidth: 150,
          resizable: true
        },
        {
         // title: '台账产线',
           title: `${this.$t('equipCheck.ListByLine')}`,
          key: 'lineName',
          align: 'center',
          minWidth: 120,
          resizable: true
        },
        {
         // title: '盘点公司',
           title: `${this.$t('equipCheck.CheckByEntity')}`,
          key: 'inventoryCompanyName',
          align: 'center',
          minWidth: 200,
          resizable: true
        },
        {
         // title: '盘点厂区',
          title: `${this.$t('equipCheck.CheckByFactory')}`,
          key: 'inventoryFactoryName',
          align: 'center',
          minWidth: 150,
          resizable: true
        },
        {
          //title: '盘点人',
           title: `${this.$t('equipCheck.CheckedBy')}`,
          key: 'inventoryByStr',
          align: 'center',
          minWidth: 180,
          resizable: true
        },
        {
          //title: '对比结果',
           title: `${this.$t('equipCheck.Result')}`,
          key: 'inventoryResultStr',
          align: 'center',
          minWidth: 120,
          resizable: true
        },
        {
          title: `${this.$t('备注')}`,
          key: 'comment',
          align: 'center',
          minWidth: 120,
          resizable: true
        }
      ],
      dataSource: [],
      pageSizeOption: [10, 20, 30, 40],
      dateTimeRange: [],
      orgList: [],
      factoryLists: [],
      companyList: [],
      factoryList: [],
      inventoryByList: [],
      noList: [],
      assetsNoList:[]
    }
  },
  created() {
    this.getTableColumnsWidth(this.columns)
    this.getCompanyList()
    this.getUsersList()
    this.getNoList()
    this.changeNum()
  },
  mounted() {
    // let itemList = JSON.parse(window.localStorage.getItem('USER_URI'))

  },
  methods: {
    reset(){
            this.searchParams = {};
            this.changeNum()
        },
    handleOutRecords() {
      let params = {};
      for (let key in this.searchParams) {
        if (key === 'orgId' && this.searchParams['orgId']) {
          const arr = this.searchParams[key]
          const {length, last = length - 1} = arr
          this.$set(params, key, arr[last])
        } else {
          if (this.searchParams[key]) {
            this.$set(params, key, this.searchParams[key])
          }
        }
      }
      const filName = '设备盘点'
      this.axios({
        method: 'post',
        url: '/dms/inventory/export',
        responseType: 'blob',
        data: {
          ...params
        }
      }).then(res => {
        fileDownload(res, filName + '.xlsx')
      })
    },
    //批量操作
    handleSelectionChange(selectionData) {
      console.log(selectionData)
      let arr = []
      selectionData.forEach(item => {
        arr.push(item.id)
      })
      this.ids = arr
    },
    //分页
    changeNum() {
      this.pageNum = 1;
      this.searchList();
    },
    changePageSize(pageSize) {
      this.pageSize = pageSize;
      this.searchList();
    },
    changePageNum(val) {
      this.pageNum = val;
      this.searchList();
    },
    searchList() {//查询列表
      const {factoryCode, companyCode, date} = this.searchParams
      const factoryCodeName = this.factoryList.find(item => item.code === factoryCode)
      const companyCodeName = this.companyList.find(item => item.code === companyCode)
      let params = {
        pageNo: this.pageNum,
        pageSize: this.pageSize,
      };
      for (let key in this.searchParams) {
        this.$set(params, key, this.searchParams[key])
      }

      params.factoryCode = factoryCodeName ? factoryCodeName.name : ""
      params.companyCode = companyCodeName ? companyCodeName.name : ""

      console.log(date)
      if (Array.isArray(date) && date.length > 1 && date[0]) {
        params['inventoryDateStar'] = moment(date[0]).format('YYYY-MM-DD HH:mm:ss')
        params['inventoryDateEnd'] = moment(date[1]).format('YYYY-MM-DD HH:mm:ss')
        delete params.date
      } else {
        delete params['inventoryDateStar']
        delete params['inventoryDateEnd']
      }
      delete params.date

      this.axios({
        method: 'post',
        url: '/dms/inventory/list',
        data: params
      }).then(res => {
        if (res.code === 200) {
          this.dataSource = res.data.list.map(item => {
            const obj = this.statusList.find(m => m.value === item.inventoryResult)
            if (obj) {
              item.statusName = obj.label
            }
            return item;
          })
          this.total = res.data.total
        } else {
          this.$Message.warning(({content: res.msg, duration: 6, closable: true}));
        }
      })
    },
    //获取公司
    getCompanyList() {
      findOrgByLevel({level: 2}).then(res => {
        if (res.code === 200) {
          this.companyList = res.data
        } else {
          this.companyList = []
          this.$Message.warning(({content: res.msg, duration: 6, closable: true}));
        }
      }).finally(() => {
        this.loading = false
      })
    },
    getFactoryList(code, listKey) {

      const obj = this.companyList.find(item => item.code === code)
      let params = {
        level: 3,
        parentId: obj.id
      }
      findOrgByLevel(params).then(res => {
        if (res.code === 200) {
          this[listKey] = res.data
        } else {
          this[listKey] = []
          this.$Message.warning(({content: res.msg, duration: 6, closable: true}));
        }
      }).finally(() => {
        this.loading = false
      })
    },
    companySelectChange() {
      if (this.searchParams.companyCode)
        this.getFactoryList(this.searchParams.companyCode, 'factoryList');
      else {
        this.factoryList = []
        this.searchParams.factoryCode = ''
      }
    },
    companySelectChanges() {
      if (this.searchParams.inventoryCompanyCode)
        this.getFactoryList(this.searchParams.inventoryCompanyCode, 'factoryLists');
      else {
        this.factoryLists = []
        this.searchParams.inventoryFactoryCode = ''
      }
    },
    getUsersList() {
      getUsers({}).then(res => {
        if (res.code === 200) {
          this.inventoryByList = res.data
        } else {
          this.inventoryByList = []
          this.$Message.warning(({content: res.msg, duration: 6, closable: true}));
        }
      })
    },
    getNoList() {
      deviceNoAndAssetsNo({deviceNo: "", assetsNo: ""}).then(res => {
        if (res.code === 200) {
          const list = res.data;
          this.noList = list.filter(item=> {
            if (item.deviceNo) return item;
          })
          this.assetsNoList = list.filter(item=> {
            if (item.assetsNo) return item;
          })
        } else {
          this.noList = []
          this.assetsNoList = []
          this.$Message.warning(({content: res.msg, duration: 6, closable: true}));
        }
      })
    },
  }
}
</script>

<style scoped lang="scss">
.picking {

  .formList {
    padding: 30px;

    .btn {
      margin-top: 20px;
      text-align: center;
      width: 100%;
      height: 40px;
    }

    .inputBorder {
      border: 1px solid #dcdee2;
      border-radius: 4px;

    }
  }


}

.ivu-input-number {
  width: -webkit-fill-available;
}

.help {
  font-family: 'Arial Normal', 'Arial', sans-serif;
  font-weight: 400;
  font-style: normal;
  font-size: 14px;
  line-height: 28px;
  //white-space: nowrap;
}
</style>

<style lang="scss">

</style>
